package com.sojson.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.ijpay.core.IJPayHttpResponse;
import com.ijpay.core.enums.RequestMethod;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.enums.WxDomain;
import com.sojson.config.exception.TransErrorCode;
import com.sojson.config.exception.TransException;
import com.sojson.constant.ConstantMessageSystemTemplate;
import com.sojson.constant.Lock;
import com.sojson.dao.PostApplyDao;
import com.sojson.dao.PostDao;
import com.sojson.entity.bo.export.MemberEp;
import com.sojson.entity.po.Member;
import com.sojson.entity.po.OrderDeposit;
import com.sojson.entity.po.Post;
import com.sojson.entity.po.PostApply;
import com.sojson.entity.vo.PostApplyVo;
import com.sojson.entity.vo.PostVo;
import com.sojson.enums.EEarnestMoneyStatus;
import com.sojson.enums.EMessageSystemType;
import com.sojson.enums.EOrderDepositDeductType;
import com.sojson.enums.EOrderDepositStatus;
import com.sojson.enums.EPostApplyHireStatus;
import com.sojson.enums.EPostApplyIsHire;
import com.sojson.enums.EPostApplyPostsStatus;
import com.sojson.enums.EPostStatus;
import com.sojson.enums.EPostType;
import com.sojson.enums.EUserAuthStatus;
import com.sojson.enums.core.EGeneralYesNo;
import com.sojson.enums.core.ERefundsStatus;
import com.sojson.service.MemberService;
import com.sojson.service.MessageSystemService;
import com.sojson.service.OrderDepositService;
import com.sojson.service.PostApplyService;
import com.sojson.util.ArithUtil;
import com.sojson.util.DateUtil;
import com.sojson.util.StringUtil;
import com.sojson.util.SystemParamUtil;
import com.sojson.util.ali.AliUtil;
import com.sojson.util.id.GUIDUtil;
import com.sojson.util.idcard.IdCardUtil;
import com.sojson.util.json.JsonUtil;
import com.sojson.util.pay.wx.WxUtil;
import com.sojson.util.pay.wx.bean.WxParamV3;
import com.sojson.util.pay.wx.bean.WxResponseV3;
import com.sojson.util.pay.wx.bean.child.param.WxPamAmount;
import com.sojson.util.pay.wx.constant.WxConstant;
import com.sojson.util.pay.wx.constant.WxCurrencyType;
import com.sojson.util.token.TokenUtil;

/**
 * 岗位应聘表Service实现类
 * 
 * @author liu
 * @date 2021-05-10
 */
@Service
public class PostApplyServiceImpl implements PostApplyService {

    @Autowired
    private PostApplyServiceImpl postApplyServiceImpl;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MessageSystemService messageSystemService;
    @Autowired
    private OrderDepositService orderDepositService;
    @Resource
    private PostApplyDao postApplyDaoImpl;
    @Resource
    private PostDao postDaoImpl;

    /**
     * 单条插入
     * 
     * @param postApply
     * @return
     */
    @Override
    public int insert(PostApply postApply) {
        int insert = postApplyDaoImpl.insert(postApply);
        return insert;
    }

    /**
     * 批量插入
     * 
     * @param postApply
     * @return
     */
    @Override
    public int insertList(PostApply postApply) {
        int insertList = postApplyDaoImpl.insertList(postApply.getPostApplys());
        return insertList;
    }

    /**
     * 通过对象批量删除(物理删除)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int deleteByDto(PostApply postApply) {
        int deleteByDto = postApplyDaoImpl.deleteByDto(postApply);
        return deleteByDto;
    }

    /**
     * 统计全部数量
     * 
     * @return
     */
    @Override
    public int countAll() {
        int countAll = postApplyDaoImpl.countAll();
        return countAll;
    }

    /**
     * 查询所有
     * 
     * @return
     */
    @Override
    public List<PostApply> findAll() {
        List<PostApply> findAll = postApplyDaoImpl.listAll();
        return findAll;
    }

    /**
     * 根据对象统计数量
     * 
     * @param postApply
     * @return
     */
    @Override
    public int countByDto(PostApply postApply) {
        int countByDto = postApplyDaoImpl.countByDto(postApply);
        return countByDto;
    }

    /**
     * 根据对象查询
     * 
     * @param postApply
     * @return
     */
    @Override
    public List<PostApply> findByDto(PostApply postApply) {
        List<PostApply> findByDto = postApplyDaoImpl.listByDto(postApply);
        return findByDto;
    }

    /**
     * 通过id删除(物理删除)
     * 
     * @param id
     * @return
     */
    @Override
    public int deleteById(Integer id) {
        int deleteById = postApplyDaoImpl.deleteById(id);
        return deleteById;
    }

    /**
     * 通过id列表删除(物理删除)
     * 
     * @param ids
     * @return
     */
    @Override
    public int deleteByIdList(List<Integer> ids) {
        int deleteByIdList = postApplyDaoImpl.deleteByIdList(ids);
        return deleteByIdList;
    }

    /**
     * 通过id更新(全部更新)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateById(PostApply postApply) {
        int updateById = postApplyDaoImpl.updateById(postApply);
        return updateById;
    }

    /**
     * 通过id列表更新(全部更新)(更新内容相同)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateStaticByIdList(PostApply postApply) {
        int updateStaticByIdList = postApplyDaoImpl.updateStaticByIdList(postApply);
        return updateStaticByIdList;
    }

    /**
     * 通过id列表更新(全部更新)(更新内容不相同)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateChangeByIdList(PostApply postApply) {
        int updateChangeByIdList = postApplyDaoImpl.updateChangeByIdList(postApply.getPostApplys());
        return updateChangeByIdList;
    }

    /**
     * 通过id更新(局部更新)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updatePartialById(PostApply postApply) {
        int updatePartialById = postApplyDaoImpl.updatePartialById(postApply);
        return updatePartialById;
    }

    /**
     * 通过id列表更新(局部更新)(更新内容相同)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateStaticPartialByIdList(PostApply postApply) {
        int updateStaticPartialByIdList = postApplyDaoImpl.updateStaticPartialByIdList(postApply);
        return updateStaticPartialByIdList;
    }

    /**
     * 通过id列表更新(局部更新)(更新内容不相同)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateChangePartialByIdList(PostApply postApply) {
        int updateChangePartialByIdList = postApplyDaoImpl.updateChangePartialByIdList(postApply.getPostApplys());
        return updateChangePartialByIdList;
    }

    /**
     * 通过id查询
     * 
     * @param id
     * @return
     */
    @Override
    public PostApply findById(Integer id) {
        PostApply findById = postApplyDaoImpl.findById(id);
        return findById;
    }

    /**
     * 通过id列表查询
     * 
     * @param ids
     * @return
     */
    @Override
    public List<PostApply> findByIdList(List<Integer> ids) {
        List<PostApply> findByIdList = postApplyDaoImpl.findByIdList(ids);
        return findByIdList;
    }

    /**
     * 通过对象查询id列表
     * 
     * @param postApply
     * @return
     */
    @Override
    public List<Integer> findIdByDto(PostApply postApply) {
        List<Integer> findIdByDto = postApplyDaoImpl.findIdByDto(postApply);
        return findIdByDto;
    }

    /**
     * 通过userId删除(物理删除)
     * 
     * @param userId
     * @return
     */
    @Override
    public int deleteByUserId(Integer userId) {
        int deleteByUserId = postApplyDaoImpl.deleteByUserId(userId);
        return deleteByUserId;
    }

    /**
     * 通过userId列表删除(物理删除)
     * 
     * @param userIds
     * @return
     */
    @Override
    public int deleteByUserIdList(List<Integer> userIds) {
        int deleteByUserIdList = postApplyDaoImpl.deleteByUserIdList(userIds);
        return deleteByUserIdList;
    }

    /**
     * 通过userId更新(全部更新)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateByUserId(PostApply postApply) {
        int updateByUserId = postApplyDaoImpl.updateByUserId(postApply);
        return updateByUserId;
    }

    /**
     * 通过userId列表更新(全部更新)(更新内容相同)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateStaticByUserIdList(PostApply postApply) {
        int updateStaticByUserIdList = postApplyDaoImpl.updateStaticByUserIdList(postApply);
        return updateStaticByUserIdList;
    }

    /**
     * 通过userId列表更新(全部更新)(更新内容不相同)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateChangeByUserIdList(PostApply postApply) {
        int updateChangeByUserIdList = postApplyDaoImpl.updateChangeByUserIdList(postApply.getPostApplys());
        return updateChangeByUserIdList;
    }

    /**
     * 通过userId更新(局部更新)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updatePartialByUserId(PostApply postApply) {
        int updatePartialByUserId = postApplyDaoImpl.updatePartialByUserId(postApply);
        return updatePartialByUserId;
    }

    /**
     * 通过userId列表更新(局部更新)(更新内容相同)
     * 
     * @param postApply
     * @return
     */
    @Override
    public int updateStaticPartialByUserIdList(PostApply postApply) {
        int updateStaticPartialByUserIdList = postApplyDaoImpl.updateStaticPartialByUserIdList(postApply);
        return updateStaticPartialByUserIdList;
    }

    /**
     * 通过userId列表更新(局部更新)(更新内容不相同)
     * 
     * @param postApplys
     * @return
     */
    @Override
    public int updateChangePartialByUserIdList(PostApply postApply) {
        int updateChangePartialByUserIdList =
            postApplyDaoImpl.updateChangePartialByUserIdList(postApply.getPostApplys());
        return updateChangePartialByUserIdList;
    }

    /**
     * 通过userId查询
     * 
     * @param userId
     * @return
     */
    @Override
    public PostApply findByUserId(Integer userId) {
        PostApply findByUserId = postApplyDaoImpl.findByUserId(userId);
        return findByUserId;
    }

    /**
     * 通过userId列表查询
     * 
     * @param userIds
     * @return
     */
    @Override
    public List<PostApply> findByUserIdList(List<Integer> userIds) {
        List<PostApply> findByUserIdList = postApplyDaoImpl.findByUserIdList(userIds);
        return findByUserIdList;
    }

    /**
     * 通过对象查询userId列表
     * 
     * @param postApply
     * @return
     */
    @Override
    public List<Integer> findUserIdByDto(PostApply postApply) {
        List<Integer> findUserIdByDto = postApplyDaoImpl.findUserIdByDto(postApply);
        return findUserIdByDto;
    }

    /**
     * 清空数据(物理清空)
     */
    @Override
    public void clear() {
        postApplyDaoImpl.clear();
    }

    /**
     * 应聘岗位
     * 
     * @param postApply
     * @return
     * @throws Exception 
     */
    @Override
    public int apply(PostApply postApply) throws Exception {
        int insert = 0;
        Integer userId = postApply.getUserId();
        Integer postId = postApply.getPostId();
        Member findById = memberService.findById(userId);
        if (EUserAuthStatus.YES.getCode() != findById.getAuthStatus()) {
            throw new TransException("用户未认证,请先认证！");
        }
        if (findById.getAge() < 16) {
            throw new TransException("未满16周岁不能应聘职位！");
        }
        if (StringUtil.isBlankString(findById.getMobile())) {
            throw new TransException(TransErrorCode.EMPTY_MOBILE.getCode(), "用户未设置手机号,请先设置手机号,后续发工资需要提供手机号！");
        }

        Post post = postDaoImpl.findById(postId);
        if (StringUtil.isBlankObject(post)) {
            throw new TransException("岗位不存在！");
        }
        if (post.getStatus() != EPostStatus.LOADING.getCode()) {
            throw new TransException("岗位不是招聘中！");
        }
        Integer type = post.getType();
        if (type != EPostType.FULL_TIME.getCode()) {
            if (post.getIsOutDate()) {
                throw new TransException("职位已停止应聘 ！");
            }

            if (EGeneralYesNo.YES.getCode() == post.getIsDeposit()) {
                if (EEarnestMoneyStatus.NO.getCode() == findById.getEarnestMoneyStatus()) {
                    throw new TransException("此岗位需要诚意金,请先缴纳诚意金！");
                }
                postApply.setHireStatus(EPostApplyHireStatus.POSTS_ING.getCode());
                postApply.setIsHire(EPostApplyIsHire.HIRE_YES.getCode());
            }
        }
        postApply.setCloseTimeReady(post.getCloseTimeReady());
        synchronized (Lock.POST_APPLY) {
            List<Integer> arrayList = new ArrayList<>();
            arrayList.add(EPostApplyPostsStatus.AUDIT.getCode());
            arrayList.add(EPostApplyPostsStatus.POSTS_YES.getCode());
            PostApplyVo pa = new PostApplyVo();
            pa.setUserId(userId);
            pa.setPostId(postId);
            pa.setPostsStatuss(arrayList);
            int countByDto = postApplyDaoImpl.count(pa);
            if (countByDto > 0) {
                throw new TransException("此岗位已应聘！");
            }
            PostApplyVo postApplyVo = new PostApplyVo();
            postApplyVo.setPostId(postId);
            postApplyVo.setIsHire(EPostApplyIsHire.HIRE_YES.getCode());
            countByDto = postApplyDaoImpl.countApply(postApplyVo);
            if (countByDto >= post.getNumPeople()) {
                throw new TransException("此岗位人数已满！");
            }

            insert = postApplyDaoImpl.insert(postApply);
            if (insert < 1) {
                throw new TransException("应聘失败,请重试！");
            }
        }

        // 发送消息
        Map<String, String> smsParams = new HashMap<>();
        // 姓名
        smsParams.put("name", findById.getName());
        // 性别
        smsParams.put("sex", IdCardUtil.getSex(findById.getSex()).getName());
        // 手机号
        smsParams.put("number", findById.getMobile());
        // 职位名称
        smsParams.put("jobname", post.getName());
        messageSystemService.send(ConstantMessageSystemTemplate.getPostApply(post, TokenUtil.getUser().getName()),
            EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(postId),
            String.valueOf(postApply.getId()), memberService.findById(post.getUserId()),
            AliUtil.getSmsTemplateCodePost(), smsParams);

        if (postApply.getHireStatus() == EPostApplyHireStatus.POSTS_ING.getCode()) {
            // 发送消息
            messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyAudit(post, true),
                EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(postId),
                String.valueOf(postApply.getId()), TokenUtil.getUser());
        }
        return insert;
    }

    /**
     * 取消应聘
     * 
     * @param postId 岗位ID
     * @return
     * @throws Exception 
     */
    @Override
    public int cancel(Integer id) throws Exception {
        synchronized (Lock.ORDER_DEPOSIT_STATUS) {
            synchronized (Lock.BALANCE_LOG) {
                return cancelGo(id);
            }
        }
    }

    @Transactional
    public int cancelGo(Integer id) throws Exception {
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("岗位应聘记录不存在！");
        }
        Member member = memberService.findById(findById.getUserId());
        if (StringUtil.isBlankObject(member)) {
            throw new TransException("应聘用户不存在！");
        }
        Post post = postDaoImpl.findById(findById.getPostId());
        if (StringUtil.isBlankObject(post)) {
            throw new TransException("岗位不存在！");
        }
        // 当前时间
        long currentTimeMillis = System.currentTimeMillis();
        // 工作开始时间
        long startDate = 0;
        // 距离工作开始时间剩余时间
        long residueDate = 0;
        Date startYearDate = post.getStartYear();
        Date startTimeTime = post.getStartTime();
        startYearDate.setHours(startTimeTime.getHours());
        startYearDate.setMinutes(startTimeTime.getMinutes());
        startYearDate.setSeconds(startTimeTime.getSeconds());
        startDate = startYearDate.getTime();
        residueDate = startDate - currentTimeMillis;

        int hours = 1000 * 60 * 60 * 12;
        if (residueDate <= 0 && findById.getHireStatus() != EPostApplyHireStatus.HIRE_ING.getCode()) {
            throw new TransException("上岗时间已到,取消失败！");
        }
        // 取消应聘
        PostApply postApply = new PostApply();
        postApply.updateInit();
        postApply.setId(id);
        postApply.setHireStatus(EPostApplyHireStatus.CANCLE.getCode());
        postApply.setPostsStatus(EPostApplyPostsStatus.CANCLE.getCode());

        Member postUser = memberService.findById(post.getUserId());
        Integer isHire = findById.getIsHire();
        if (EPostApplyIsHire.HIRE_ING.getCode() == isHire || post.getType() == EPostType.FULL_TIME.getCode()
            || post.getIsDeposit() == EGeneralYesNo.NO.getCode()
            || member.getEarnestMoneyStatus() == EEarnestMoneyStatus.NO.getCode()) {
            // 修改应聘状态
            int updatePartialById = postApplyDaoImpl.updatePartialById(postApply);
            if (updatePartialById < 1) {
                throw new TransException("修改失败，请重试！");
            }
            // 发送消息
            messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyCancel(post, member.getName()),
                EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(findById.getPostId()),
                String.valueOf(findById.getId()), postUser);
            return updatePartialById;
        }
        OrderDeposit orderDeposit = orderDepositService.getInfoByOrderSn(member.getEarnestMoneyOrderNo());
        if (StringUtil.isBlankObject(orderDeposit)
            || orderDeposit.getStatus() != EOrderDepositStatus.RETU_YES.getCode()) {
            // 修改应聘状态
            int updatePartialById = postApplyDaoImpl.updatePartialById(postApply);
            if (updatePartialById < 1) {
                throw new TransException("修改失败，请重试！");
            }
            // 发送消息
            messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyCancel(post, member.getName()),
                EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(findById.getId()), postUser);
            // 修改诚意金状态
            Member m = new Member();
            m.updateInit();
            m.setId(member.getId());
            m.setEarnestMoneyStatus(EEarnestMoneyStatus.NO.getCode());
            int updateMember = memberService.updatePartialById(m);
            if (updateMember < 1) {
                throw new TransException("修改失败，请重试！");
            }
            return updatePartialById;
        }

        int updatePartial = postApplyDaoImpl.updatePartialById(postApply);
        if (updatePartial < 1) {
            throw new TransException("取消失败，请重试！");
        }
        // 发送消息
        messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyCancel(post, member.getName()),
            EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(findById.getId()), postUser);

        // 大于24小时直接结束
        if (residueDate >= hours * 2) {
            return updatePartial;
        }

        Member m = new Member();
        m.updateInit();
        m.setId(member.getId());
        m.setEarnestMoneyStatus(EEarnestMoneyStatus.NO.getCode());
        int updatePartialById = memberService.updatePartialById(m);
        if (updatePartialById < 1) {
            throw new TransException("诚意金状态修改失败，请重试！");
        }

        int code = EOrderDepositDeductType.ALL.getCode();
        BigDecimal total = orderDeposit.getPayTotal();
        String msg = "取消职位，扣除全部诚意金！";
        // 扣除诚意金
        if (residueDate >= hours) {
            int bigDollarToIntPenny = ArithUtil.bigDollarToIntPenny(total);
            int chu = bigDollarToIntPenny / 2;
            int jian = bigDollarToIntPenny - chu;
            if (chu == jian) {
                total = ArithUtil.intPennyToBigDollar(chu);
            } else if (chu < jian) {
                total = ArithUtil.intPennyToBigDollar(chu + 1);
            } else {
                total = ArithUtil.intPennyToBigDollar(chu);
            }
            code = EOrderDepositDeductType.HALF.getCode();
            msg = "取消职位，扣除一半诚意金！";
        }

        OrderDeposit od = new OrderDeposit();
        od.updateInit();
        od.setId(orderDeposit.getId());
        od.setStatus(EOrderDepositStatus.DEDUCT.getCode());
        od.setDeductType(code);
        od.setDeductPostApplyId(id);
        od.setDeductMessage(msg);
        if (code == EOrderDepositDeductType.HALF.getCode()) {
            od.setIsRefunds(ERefundsStatus.ING.getCode());
            od.setDeductTotal(orderDeposit.getPayTotal().subtract(total));
            od.setRefundTotal(total);
            od.setRefundSn(GUIDUtil.generateGuid());
        } else {
            od.setDeductTotal(orderDeposit.getPayTotal());
        }
        int updateByOdId = orderDepositService.updatePartialById(od);
        if (updateByOdId < 1) {
            throw new TransException("操作失败,请重试！");
        }

        od.setPayTotal(orderDeposit.getPayTotal());
        // 发送消息
        messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyCancel(post, od),
            EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(postApply.getId()), member);

        // 退款
        if (code == EOrderDepositDeductType.HALF.getCode()) {
            // 获取微信接口参数
            Map<String, String> config = SystemParamUtil.gets();
            String mchid = config.get(WxConstant.MCHID_CACHE_NAME);
            String serialNo = config.get(WxConstant.CA_SERIALNO_CACHE_NAME);

            // 拼装参数
            WxPamAmount wxPamAmount = new WxPamAmount();
            wxPamAmount.setTotal(ArithUtil.bigDollarToIntPenny(orderDeposit.getPayTotal()));
            wxPamAmount.setRefund(ArithUtil.bigDollarToIntPenny(od.getRefundTotal()));
            wxPamAmount.setCurrency(WxCurrencyType.CNY);
            WxParamV3 wxParam = new WxParamV3();
            wxParam.setAmount(wxPamAmount);
            wxParam.setOutTradeNo(orderDeposit.getOrderSn());
            wxParam.setOutRefundNo(od.getRefundSn());
            wxParam.setNotifyUrl(WxConstant.NOTIFY_URL_ORDER_DEPOSIT_CANCEL);
            // 调用退款接口
            IJPayHttpResponse v3 =
                WxPayApi.v3(RequestMethod.POST, WxDomain.CHINA.getType(), WxApiType.DOMESTIC_REFUNDS.getType(), mchid,
                    serialNo, null, WxUtil.PRIVATE_KEY, JSONObject.toJSONString(wxParam));
            // 获取响应结果
            WxResponseV3 jsonToObject = JsonUtil.jsonToObject(v3.getBody(), WxResponseV3.class);
            String status = jsonToObject.getStatus();
            if (!"SUCCESS".equals(status) && !"PROCESSING".equals(status)) {
                throw new TransException("退款失败: " + jsonToObject.getMessage());
            }
        }
        return updatePartial;
    }

    /**
     * 查看应聘的人列表
     * 
     * @param postApply
     * @return
     */
    @Override
    public List<PostApplyVo> list(PostApplyVo postApply) {
        return postApplyDaoImpl.list(postApply);
    }

    /**
     * 查看应聘的人列表
     * 
     * @param postApply
     * @return
     */
    @Override
    public List<MemberEp> listExport(PostApplyVo postApply) {
        List<MemberEp> listMemberAll = postApplyDaoImpl.listMemberAll(postApply);
        return listMemberAll;
    }

    /**
     * 统计应聘的人
     * 
     * @param postApply
     * @return
     */
    @Override
    public int count(PostApplyVo postApply) {
        return postApplyDaoImpl.count(postApply);
    }

    /**
     * 录用
     * @throws Exception 
     */
    @Override
    @Transactional
    public int hireYes(PostApply postApply) throws Exception {
        Integer id = postApply.getId();
        Integer userId = TokenUtil.getUserId();
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("应聘记录不存在！");
        }
        Integer postId = findById.getPostId();
        Post post = postDaoImpl.findById(postId);
        if (StringUtil.isBlankObject(post)) {
            throw new TransException("岗位不存在！");
        }
        if (post.getUserId().intValue() != userId) {
            throw new TransException("请不要操作别人的岗位！");
        }

        if (EPostApplyHireStatus.HIRE_ING.getCode() != findById.getHireStatus()) {
            throw new TransException("应聘状态不是待录用！");
        }

        PostApply pa = new PostApply();
        pa.updateInit();
        pa.setId(id);
        pa.setHireStatus(EPostApplyHireStatus.POSTS_ING.getCode());
        pa.setIsHire(EPostApplyIsHire.HIRE_YES.getCode());
        int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
        if (updatePartialById < 1) {
            throw new TransException("操作失败,请重试！");
        }

        // 发送消息
        messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyAudit(post, true),
            EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(postId), String.valueOf(id),
            memberService.findById(findById.getUserId()));
        return updatePartialById;
    }

    /**
     * 不录用
     * @throws Exception 
     */
    @Override
    @Transactional
    public int hireNo(PostApply postApply) throws Exception {
        Integer id = postApply.getId();
        Integer userId = TokenUtil.getUserId();
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("应聘记录不存在！");
        }
        Integer postId = findById.getPostId();
        Post post = postDaoImpl.findById(postId);
        if (StringUtil.isBlankObject(post)) {
            throw new TransException("岗位不存在！");
        }
        if (post.getUserId().intValue() != userId) {
            throw new TransException("请不要操作别人的岗位！");
        }

        if (EPostApplyHireStatus.HIRE_ING.getCode() != findById.getHireStatus()) {
            throw new TransException("应聘状态不是待录用！");
        }

        PostApply pa = new PostApply();
        pa.updateInit();
        pa.setId(id);
        pa.setHireStatus(EPostApplyHireStatus.HIRE_NO.getCode());
        pa.setIsHire(EPostApplyIsHire.HIRE_NO.getCode());
        int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
        if (updatePartialById < 1) {
            throw new TransException("操作失败,请重试！");
        }

        // 发送消息
        messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyAudit(post, false),
            EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(postId), String.valueOf(id),
            memberService.findById(findById.getUserId()));
        return updatePartialById;
    }

    /**
     * 不录用
     * @throws Exception 
     */
    @Override
    @Transactional
    public int hireNoWeb(PostApply postApply) throws Exception {
        Integer id = postApply.getId();
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("应聘记录不存在！");
        }
        Integer postId = findById.getPostId();
        PostApply pa = new PostApply();
        pa.updateInit();
        pa.setId(id);
        pa.setHireStatus(EPostApplyHireStatus.HIRE_NO.getCode());
        pa.setIsHire(EPostApplyIsHire.HIRE_NO.getCode());

        Post post = postDaoImpl.findById(postId);
        if (StringUtil.isBlankObject(post)) {
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return updatePartialById;
        }

        if (EPostApplyHireStatus.HIRE_ING.getCode() != findById.getHireStatus()) {
            throw new TransException("应聘状态不是待录用！");
        }

        int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
        if (updatePartialById < 1) {
            throw new TransException("操作失败,请重试！");
        }

        // 发送消息
        messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyAudit(post, false),
            EMessageSystemType.POST.getCode(), post.getType(), String.valueOf(postId), String.valueOf(id),
            memberService.findById(findById.getUserId()));
        return updatePartialById;
    }

    /**
     * 已上岗
     * 
     * @param postApply
     * @return
     * @throws IOException 
     */
    @Override
    public int postsYes(PostApply postApply) throws IOException {
        Integer id = postApply.getId();
        Integer userId = TokenUtil.getUserId();
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("应聘记录不存在！");
        }
        Integer postId = findById.getPostId();
        Post post = postDaoImpl.findById(postId);
        if (StringUtil.isBlankObject(post)) {
            throw new TransException("岗位不存在！");
        }
        if (post.getUserId().intValue() != userId) {
            throw new TransException("请不要操作别人的岗位！");
        }

        if (EPostApplyHireStatus.POSTS_ING.getCode() != findById.getHireStatus()) {
            throw new TransException("应聘状态不是待上岗 ！");
        }
        int code = EGeneralYesNo.YES.getCode();
        if (code == findById.getBossIsUpdateStatus()) {
            throw new TransException("只能修改一次上岗状态,如果要重新修改请联系管理员 ！");
        }

        PostApply pa = new PostApply();
        pa.updateInit();
        pa.setId(id);
        pa.setHireStatus(EPostApplyHireStatus.PAY_ING.getCode());
        pa.setPostsStatus(EPostApplyPostsStatus.POSTS_YES.getCode());
        pa.setBossIsUpdateStatus(code);
        int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
        if (updatePartialById < 1) {
            throw new TransException("操作失败,请重试！");
        }
        return updatePartialById;
    }

    /**
     * 未上岗
     * 
     * @param postApply
     * @return
     * @throws Exception 
     */
    @Override
    public int postsNo(PostApply postApply) throws Exception {
        Integer id = postApply.getId();
        Integer userId = TokenUtil.getUserId();
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("应聘记录不存在！");
        }
        Integer postId = findById.getPostId();
        Post post = postDaoImpl.findById(postId);
        if (StringUtil.isBlankObject(post)) {
            throw new TransException("岗位不存在！");
        }
        if (post.getUserId().intValue() != userId) {
            throw new TransException("请不要操作别人的岗位！");
        }

        if (EPostApplyHireStatus.POSTS_ING.getCode() != findById.getHireStatus()) {
            throw new TransException("应聘状态不是待上岗 ！");
        }
        int code = EGeneralYesNo.YES.getCode();
        if (code == findById.getBossIsUpdateStatus()) {
            throw new TransException("只能修改一次上岗状态,如果要重新修改请联系管理员 ！");
        }
        if (post.getType() != EPostType.FULL_TIME.getCode()) {
            Date startYear = post.getStartYear();
            Date startTime = post.getStartTime();
            startYear.setHours(startTime.getHours());
            startYear.setMinutes(startTime.getMinutes());
            startYear.setSeconds(startTime.getSeconds());
            if (DateUtil.nowLong() < startYear.getTime()) {
                throw new TransException("上岗时间未到 ！");
            }
        }

        PostApply pa = new PostApply();
        pa.updateInit();
        pa.setId(id);
        pa.setHireStatus(EPostApplyHireStatus.POSTS_NO.getCode());
        pa.setPostsStatus(EPostApplyPostsStatus.POSTS_NO.getCode());
        pa.setBossIsUpdateStatus(code);

        // 是否需要诚意金
        if (post.getIsDeposit() != code) {
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return updatePartialById;
        }
        // 是否是全职
        if (post.getType() == EPostType.FULL_TIME.getCode()) {
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return updatePartialById;
        }

        synchronized (Lock.ORDER_DEPOSIT_STATUS) {
            // 修改应聘状态
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return postApplyServiceImpl.postsNoGo(findById, post);
        }
    }

    @Transactional
    public int postsNoGo(PostApply postApply, Post post) throws Exception {
        // 修改诚意金状态
        Member findById = memberService.findById(postApply.getUserId());
        int code = EEarnestMoneyStatus.NO.getCode();
        if (findById.getEarnestMoneyStatus() == code) {
            return 1;
        }
        Member m = new Member();
        m.updateInit();
        m.setId(findById.getId());
        m.setEarnestMoneyStatus(code);
        int updatePartialById = memberService.updatePartialById(m);
        if (updatePartialById < 1) {
            throw new TransException("操作失败,请重试！");
        }

        // 修改诚意金状态
        OrderDeposit infoByOrderSn = orderDepositService.getInfoByOrderSn(findById.getEarnestMoneyOrderNo());
        int retuYes = EOrderDepositStatus.RETU_YES.getCode();
        if (StringUtil.isBlankObject(infoByOrderSn) || infoByOrderSn.getStatus() != retuYes) {
            return updatePartialById;
        }
        OrderDeposit od = new OrderDeposit();
        od.updateInit();
        od.setId(infoByOrderSn.getId());
        od.setStatus(EOrderDepositStatus.DEDUCT.getCode());
        od.setDeductType(EOrderDepositDeductType.ALL.getCode());
        od.setDeductTotal(infoByOrderSn.getPayTotal());
        od.setDeductPostApplyId(postApply.getId());
        od.setDeductMessage("未到岗,扣除全部诚意金！");
        int updateByOdId = orderDepositService.updatePartialById(od);
        if (updateByOdId < 1) {
            throw new TransException("操作失败,请重试！");
        }

        // 发送消息
        if (retuYes == infoByOrderSn.getStatus()) {
            // 发送消息
            messageSystemService.send(ConstantMessageSystemTemplate.getPostApplyPostsNo(post),
                EMessageSystemType.DEPOSIT_CANCEL.getCode(), post.getType(), String.valueOf(postApply.getPostId()),
                String.valueOf(postApply.getId()), findById);
        }
        return updatePartialById;
    }

    /**
     * 已上岗
     * 
     * @param postApply
     * @return
     * @throws IOException 
     */
    @Override
    public int postsYesWeb(PostApply postApply) throws IOException {
        Integer id = postApply.getId();
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("应聘记录不存在！");
        }
        if (findById.getBossIsUpdateStatus() == EGeneralYesNo.NO.getCode()) {
            throw new TransException("请先让中介操作岗位！");
        }

        PostApply pa = new PostApply();
        pa.setId(postApply.getId());
        pa.setHireStatus(EPostApplyHireStatus.PAY_ING.getCode());
        return postApplyDaoImpl.updatePartialById(pa);
    }

    /**
     * 未上岗
     * 
     * @param postApply
     * @return
     * @throws Exception 
     */
    @Override
    public int postsNoWeb(PostApply postApply) throws Exception {
        Integer id = postApply.getId();
        PostApply findById = postApplyDaoImpl.findById(id);
        if (StringUtil.isBlankObject(findById)) {
            throw new TransException("应聘记录不存在！");
        }
        // if (findById.getBossIsUpdateStatus() == EGeneralYesNo.NO.getCode()) {
        // throw new TransException("请先让中介操作岗位");
        // }

        int code = EGeneralYesNo.YES.getCode();
        PostApply pa = new PostApply();
        pa.updateInit();
        pa.setId(id);
        pa.setHireStatus(EPostApplyHireStatus.POSTS_NO.getCode());
        pa.setPostsStatus(EPostApplyPostsStatus.POSTS_NO.getCode());

        Integer postId = findById.getPostId();
        Post post = postDaoImpl.findById(postId);
        if (StringUtil.isBlankObject(post)) {
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return updatePartialById;
        }
        if (post.getType() != EPostType.FULL_TIME.getCode()) {
            Date startYear = post.getStartYear();
            Date startTime = post.getStartTime();
            startYear.setHours(startTime.getHours());
            startYear.setMinutes(startTime.getMinutes());
            startYear.setSeconds(startTime.getSeconds());
            if (DateUtil.nowLong() < startYear.getTime()) {
                throw new TransException("上岗时间未到 ！");
            }
        }

        // 是否需要诚意金
        if (post.getIsDeposit() != code) {
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return updatePartialById;
        }
        // 是否是全职
        if (post.getType() == EPostType.FULL_TIME.getCode()) {
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return updatePartialById;
        }

        synchronized (Lock.ORDER_DEPOSIT_STATUS) {
            // 修改应聘状态
            int updatePartialById = postApplyDaoImpl.updatePartialById(pa);
            if (updatePartialById < 1) {
                throw new TransException("操作失败,请重试！");
            }
            return postApplyServiceImpl.postsNoGo(findById, post);
        }
    }

    /**
     * 用户查看应聘的岗位
     * 
     * @param postApply
     * @return
     */
    @Override
    public List<PostVo> listPost(PostApplyVo postApply) {
        return postDaoImpl.listByPostApply(postApply);
    }

    /**
     * 通过id查询
     * 
     * @param id
     * @return
     */
    @Override
    public PostApplyVo getInfo(Integer id) {
        return postApplyDaoImpl.getInfo(id);
    }

    /**
     * 用户首页统计
     * 
     * @return
     */
    @Override
    public Map<String, Integer> countUser(PostApplyVo postApply) {
        return postApplyDaoImpl.countUser(postApply);
    }

}